#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 8888
#define BUFFER_SIZE 1024
using namespace std;

int main()
{
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];

    // 创建监听套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket error");
        exit(EXIT_FAILURE);
    }
    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定监听套接字到指定地址和端口
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("bind error");
        exit(EXIT_FAILURE);
    }
    // 监听连接请求
    if (listen(server_fd, 5) < 0)
    {
        perror("listen error");
        exit(EXIT_FAILURE);
    }
    cout << "服务器正在监听" << PORT << "端口" << endl;
    // 接受连接
    if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len)) < 0)
    {
        perror("accept error");
        exit(EXIT_FAILURE);
    }
    cout<<"客户端已连接"<<endl;
    // 接收客户端数据
    int n = recv(client_fd, buffer, BUFFER_SIZE, 0);
    if (n <= 0)
    {
        perror("recv failed");
        exit(1);
    }
    buffer[n] = '\0';
    cout << "客户端发来：" << buffer << endl;
    // 发送数据
    const char *message = "你好 客户端（来自服务器）";
    n = send(client_fd, message, strlen(message), 0);
    if (n < 0)
    {
        perror("send failed");
        exit(1);
    }
    // 关闭套接字
    close(client_fd);
    close(server_fd);

    return 0;
}